package com.sp2p.action.front;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.zxing.Result;
import com.renren.api.client.services.UserService;
import com.shove.Convert;
import com.shove.data.DataException;
import com.shove.security.Encrypt;
import com.shove.util.SqlInfusion;
import com.shove.web.util.JSONUtils;
import com.sp2p.constants.IAmountConstants;
import com.sp2p.constants.IConstants;
import com.sp2p.entity.User;
import com.sp2p.service.AssignmentDebtService;
import com.sp2p.service.AuctionDebtService;
import com.sp2p.service.SelectedService;
import com.sp2p.service.admin.PlatformCostService;
import com.sp2p.util.DateUtil;

/**
 * 债权转让
 */
public class HomeDebtAction extends BaseFrontAction {

	public static Log log = LogFactory.getLog(HomeDebtAction.class);
	private static final long serialVersionUID = 1L;

	private AssignmentDebtService assignmentDebtService;

	private AuctionDebtService auctionDebtService;

	private SelectedService selectedService;
	
	private PlatformCostService platformCostService;

	private List<Map<String, Object>> auctionDaysList;
	
	public void setPlatformCostService(PlatformCostService platformCostService) {
		this.platformCostService = platformCostService;
	}
	
	public void getCanLoanInvestorsList() throws Exception {
		int borrowProduct = Convert.strToInt(request("borrowProduct"), -1);
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		long userId = this.getUserId();
		
		try {
			assignmentDebtService.queryCanAssignmentDebt(userId, borrowProduct, pageBean);
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
		}
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("voList", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("voList", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		JSONUtils.printObject(obj);
		
	}
	
	public void calculateSoldPriceByDiscount() throws Exception {
		long  loanInvestorId= Convert.strToLong(request("loanInvestorId"), -1);
		String discount = SqlInfusion.FilteSqlInfusion(request("discount"));
		
		Map<String, String> map = new HashMap<String, String>();
		
		try {
			map = assignmentDebtService.calculateSoldPriceByDiscount(loanInvestorId, discount);
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
		}
		
		JSONObject obj = new JSONObject();
		if( map != null){
			obj.put("soldPrice", map.get("soldPrice"));
		}else{
			obj.put("soldPrice", "");
		}
		
		JSONUtils.printObject(obj);
		
	}
	
	public void redeemLoanInvestor() throws Exception {
		JSONObject obj = new JSONObject();
		String ids = SqlInfusion.FilteSqlInfusion(request("loanInvestorIdStr"));
		String discountStr = SqlInfusion.FilteSqlInfusion(request("discountStr"));
		String payPassword = SqlInfusion.FilteSqlInfusion(request("payPassword"));
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Map<String, String> userMap = assignmentDebtService.queryUserById(user.getId());
		
		if(user.getId() < 0){
			obj.put("result", "needLogin");
			JSONUtils.printObject(obj);
			return;
		}
		
		if ("1".equals(IConstants.ENABLED_PASS)){ //1为默认启用
			payPassword =  Encrypt.MD5(payPassword.trim());
		}else{
			payPassword =  Encrypt.MD5(payPassword.trim()+IConstants.PASS_KEY);
		}
		if(!payPassword.equals(userMap.get("dealpwd"))){
			obj.put("result", "payPasswordFailed");
			obj.put("msg", "交易密码错误");
			JSONUtils.printObject(obj);
			return;
		}
		
		Map<String, String> reslutMap = new HashMap<String, String>();
		reslutMap = assignmentDebtService.addAssignmentDebt(ids,discountStr,user.getId());
		
		if(reslutMap != null){
			int result = Convert.strToInt(reslutMap.get("result"), -1);
			if(result > 0){
				obj.put("result", "success");
			}else {
				obj.put("result", "failed");
				obj.put("msg", reslutMap.get("msg"));
			}
		}else{
			obj.put("result", "failed");
			obj.put("msg", "投资赎回记录添加失败！");
		}
		
		JSONUtils.printObject(obj);
	}
	
	public void getLoanInvestorsListByStatus() throws Exception {
		int borrowProduct = Convert.strToInt(request("borrowProduct"), -1);
		int status = Convert.strToInt(request("status"), -1);
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		long userId = this.getUserId();
		
		try {
			assignmentDebtService.queryAssignmentDebtByStatus(userId, borrowProduct,status, pageBean);
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
		}
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("voList", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("voList", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		JSONUtils.printObject(obj);
		
	}
	
	public void cancelRedeem() throws Exception {
		long loanDebtId = Convert.strToLong(request("loanDebtId"), -1);
		long userId = this.getUserId();
		JSONObject obj = new JSONObject();
		
		try {
			long result = assignmentDebtService.cancelRedeem(loanDebtId,userId);
			
			if( result > 0){
				obj.put("result", "success");
			}else{
				obj.put("result", "failed");
			}
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
		}
		
		JSONUtils.printObject(obj);
		
	}
	
	public void getFinanceYebListByStatus() throws Exception {
		String status = SqlInfusion.FilteSqlInfusion(request("status"));
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		long userId = this.getUserId();
		
		try {
			assignmentDebtService.queryYebCanAssignmentDebt(userId, status, pageBean);
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
		}
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("voList", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("voList", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		JSONUtils.printObject(obj);
		
	}
	
	public void applyToRedeemFinanceYebInvestor() throws Exception {
		JSONObject obj = new JSONObject();
		String ids = SqlInfusion.FilteSqlInfusion(request("financeYebInvestorIdStr"));
		String payPassword = SqlInfusion.FilteSqlInfusion(request("payPassword"));
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		Map<String, String> userMap = assignmentDebtService.queryUserById(user.getId());
		
		if(user.getId() < 0){
			obj.put("result", "needLogin");
			JSONUtils.printObject(obj);
			return;
		}
		if ("1".equals(IConstants.ENABLED_PASS)){ //1为默认启用
			payPassword =  Encrypt.MD5(payPassword.trim());
		}else{
			payPassword =  Encrypt.MD5(payPassword.trim()+IConstants.PASS_KEY);
		}
		if(!payPassword.equals(userMap.get("dealpwd"))){
			obj.put("result", "payPasswordFailed");
			obj.put("msg", "交易密码错误");
			JSONUtils.printObject(obj);
			return;
		}
		
		Map<String, String> reslutMap = new HashMap<String, String>();
		reslutMap = assignmentDebtService.addAssignmentDebtYeb(ids,user.getId());
		
		if(reslutMap != null){
			int result = Convert.strToInt(reslutMap.get("result"), -1);
			if(result > 0){
				obj.put("result", "success");
			}else {
				obj.put("result", "failed");
				obj.put("msg", reslutMap.get("msg"));
			}
		}else{
			obj.put("result", "failed");
			obj.put("msg", "投资赎回记录添加失败！");
		}
		
		JSONUtils.printObject(obj);
	}

	public void setAssignmentDebtService(
			AssignmentDebtService assignmentDebtService) {
		this.assignmentDebtService = assignmentDebtService;
	}

	public void setAuctionDebtService(AuctionDebtService auctionDebtService) {
		this.auctionDebtService = auctionDebtService;
	}

	public List<Map<String, Object>> getAuctionDaysList() throws Exception {
		auctionDaysList = selectedService.getDebtAuctionDays();
		return auctionDaysList;
	}

	public void setAuctionDaysList(List<Map<String, Object>> auctionDaysList) {
		this.auctionDaysList = auctionDaysList;
	}

	public void setSelectedService(SelectedService selectedService) {
		this.selectedService = selectedService;
	}

}
